/*
 * Title: WADS
 * Description: Web-based Auto flow Documents System
 * Copyright: 2007
 * Company: CoE
 * @author: Mr.Nattasan Wang-Aphisit
 * @version 1.1
 */

package wads.servlet;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import wads.com.AutoDocumentTransaction;
import wads.com.DocumentTemplateInfo;
import wads.com.UserInfo;
import wads.com.WADTools;

public class ManageSuccessDocServlet extends HttpServlet {
  private static final long serialVersionUID = 8738161887193480375L;
  
  private static final String CONTENT_TYPE = WADTools.SERVLET_CONTENT_TYPE;
  /**Initialize global variables*/
  public final int USER = 1;
  public final int FULLUSER = 2;
  String app_Path;

  Vector successFile;
  Vector documentIDFile;
  Vector successFileList = new Vector();

  AutoDocumentTransaction adTran;
  DocumentTemplateInfo dtInfo;

  //List of String
  String Transaction_ID;
  String template_ID;
  String template_Name;
  String ownerName;
  String currentUser;
  String sendDate;
  String updateDate;
  String createdTime;
  String submitTime;
  Calendar cal_ct;

  ServletOutputStream sos;
  UserInfo uiRestrictUser;
  String fullNameRestrict;
  UserInfo uiPowerUser;

  public void init(ServletConfig config) throws ServletException {
    super.init(config);
  }
  /**Process the HTTP Get request*/
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType(CONTENT_TYPE);
    //app_Path = this.getInitParameter("app_Path");
    app_Path = WADTools.APP_PATH;
    sos = response.getOutputStream();
    //Read Beginning of HTML file to create Head of table
    this.readBeginninghtml();
    successFileList = this.listFileName();
    this.fillDataAll(successFileList);
    sos.close();
  }

  /**Clean up resources*/
  public void destroy() {
  }

  public Vector listFileName(){
    Vector<String> successFile = new Vector<String>();
    File doc_Path = new File(app_Path+"res/docs/SuccessDocument/");
    if(doc_Path.isDirectory()){
      File[] listUserPath = doc_Path.listFiles();
      for(int i=0; i<listUserPath.length ;i++)
        successFile.add(listUserPath[i].getName());
    }
    return successFile;
  }

  public void readBeginninghtml(){
    File htmlFile = new File("success_list.html");
    String temp = null;
    byte[] buf = new byte[1024];
    boolean check = true;
    try{
        BufferedReader br = new BufferedReader(new FileReader(htmlFile));
        while((temp = br.readLine()) != null){
          if((temp.indexOf("hiddenField") == -1) && check){
            buf = temp.getBytes();
            sos.write(buf,0,temp.length());
          }else{
            check = false;
          }
        }
        br.close();
      }catch(Exception e){
        System.out.println(e);
      }
  }

  public void fillDataAll(Vector successFileToShow){
     //String user = null;
     String BGColor;
       for(int i=0; i<successFileToShow.size(); i++){
        //Set Color for Light Gray and Dark Gray
        if(i%2 != 0) BGColor = "#F0F0F0";
        else BGColor = "#CCCCCC";

        try{
          ObjectInputStream ois = new ObjectInputStream(
            new FileInputStream(app_Path+"res/docs/SuccessDocument/" + successFileToShow.elementAt(i)));
          adTran = (AutoDocumentTransaction)ois.readObject();
          Transaction_ID = adTran.getTransaction_ID();
          template_ID = adTran.getTemplate_ID();
          template_Name = adTran.getTemplate_Name();
          //Get Full Name of User
          ownerName = this.getFullNameofRestrictedUser(adTran.getOwner_Name());
          //Get createdTime
          createdTime = this.getCreatedTime(adTran.getCreated_Date());
          sendDate = adTran.getCreated_Date().toString();
          updateDate = adTran.getCurrentTime().toString();

          ObjectInputStream oisa = new ObjectInputStream(
            new FileInputStream(app_Path+"res/docs/activeDocTemplate/" + template_ID + "/docTemplate.info"));
          dtInfo = (DocumentTemplateInfo)oisa.readObject();
          oisa.close();
          String docName = dtInfo.getTemplate_Name();
          docName = "<a href=\"servlet/show?ID=" + adTran.getTransaction_ID() + "&user=SuccessDocument" + "\">" + docName + "</a>";

          //delete document
          String delete = "<a href=\"servlet/deletesuccess?ID=" + adTran.getTransaction_ID()+ "\">" + "<img src=../images/bin.gif width=\"20\" height=\"20\">" + "</a>";

          String temp = " <tr bgcolor=" + BGColor + "><td width=70 align=center>" + Transaction_ID +
            "</td><td width=300>&nbsp;&nbsp;&nbsp;" + docName +
            "</td><td width=300>&nbsp;&nbsp;&nbsp;" + ownerName +
            "</td><td width=70 align=center>" + createdTime +
            "</td><td width=50>" + delete + "</td></tr>";

          sos.write(temp.getBytes(),0,temp.length());
          ois.close();
        }
        catch(Exception e) {
          System.out.println("Exception thrown from ManageSuccessDocServlet.fillDataAll()");
          e.printStackTrace();
        }

     }
  }

  public String getFullNameofRestrictedUser(String name){
    String restrictUserFile = app_Path+"res/user/RestrictUser/RestrictUser.org";

    //Read Object of RestrictUser
    try{
      ObjectInputStream ois = new ObjectInputStream(new FileInputStream(restrictUserFile));
      uiRestrictUser = (UserInfo)ois.readObject();
      ois.close();
    }catch(Exception e){System.out.println(e);}

    if(!uiRestrictUser.isEmpty()){
       for(int i=0; i<uiRestrictUser.getSize(); i++){
          if(name.equals(uiRestrictUser.getUserDataAt(i).getUsername()))
            fullNameRestrict = uiRestrictUser.getUserDataAt(i).getName();
       }
    }
    return fullNameRestrict;
  }

  public String getCreatedTime(Date createdTime){
    cal_ct.setTime(createdTime);
    int date = cal_ct.get(Calendar.DAY_OF_MONTH);
    int month = cal_ct.get(Calendar.MONTH);
    int year = cal_ct.get(Calendar.YEAR)-57;

    return date + "/" + month + "/" + year;
  }

  public String getSubmitTime(Calendar submitTime){
    int date = submitTime.get(Calendar.DAY_OF_MONTH);
    int month = submitTime.get(Calendar.MONTH);
    int year = submitTime.get(Calendar.YEAR)-57;

    return date + "/" + month + "/" + year;
  }
}
